package cn.tedu.egarticle0811.base.exception;

import cn.tedu.egarticle0811.base.response.JsonResult;
import cn.tedu.egarticle0811.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler{
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.debug("发生参数验证异常：{}", ex.getMessage());
        String  data = ex.getBindingResult().getFieldError().getDefaultMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex) {
        log.debug("发生参数验证异常：{}", ex.getMessage());
        String  data = ex.getConstraintViolations().iterator().next().getMessage();
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
}
